package io.snow.mybatis.core.utils;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import io.snow.mybatis.admin.service.AdminService;
import io.snow.mybatis.core.common.Const;
import io.snow.mybatis.core.entity.UserInfo;
import io.snow.mybatis.core.redis.Redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class UserCacheUtils {

    static UserCacheUtils ME;

    @PostConstruct
    public void init() { ME = this; }

    @CreateCache(name = Const.ADMIN_USER_NAME_CACHE_NAME, expire = 3, timeUnit = TimeUnit.DAYS)
    private Cache<Long, String> userCache;

    @CreateCache(name = Const.ADMIN_DEPT_NAME_CACHE_NAME, expire = 3, timeUnit = TimeUnit.DAYS)
    private Cache<Integer, String> depCache;

    @Autowired
    private AdminService AdminService;

    @Autowired
    private Redis redis;

    /*
     * 根据用户ID获取用户名列表，使用 , 号合并
     */
    public static <T> String getUserNameList(List<T> userIds) {
        List<String> stringList = new ArrayList<>();
        for (T obj : userIds) {
            String name;
            if (obj instanceof Long) {
                name = getUserName((Long) obj);
            } else if (obj instanceof String) {
                name = getUserName(Long.valueOf((String) obj));
            } else {
                name = "";
            }
            if (!"".equals(name)) {
                stringList.add(name);
            }
        }
        return stringList.size() > 0 ? String.join(Const.SEPARATOR, stringList) : "";
    }

    /*
     * 根据用户ID获取用户名
     */
    public static UserInfo getUserInfo(Long userId) { return ME.AdminService.getUserInfo(userId).getData(); }

    /*
     * 根据用户ID获取用户名
     */
    public static String getUserName(Long userId) {
        if (userId == null) {
            return "";
        }
        Long key = userId;
        String name = ME.userCache.get(key);
        if (name == null) {
            name = ME.AdminService.queryUserName(userId).getData();
            ME.userCache.put(key, name);
        }
        return name;
    }
}
